package edu.xhu.minio.util;

import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;

/**
 * 目前只支持死磁盘，磁盘有变动算法可能出错
 */
@Slf4j
public class LinuxStateForShell {
    private static final String CPU_MEM_SHELL = "top -b -n 1";
    private static final String FILES_SHELL = "df -hl";
    private static final String[] COMMANDS = {CPU_MEM_SHELL, FILES_SHELL};
    private static final String LINE_SEPARATOR = System.getProperty("line.separator");

    private static final String MSG = "/dev/vda1";

    private static Session session;

    /**
     * 连接到指定的host
     */
    private static boolean connect(String user, String passwd, String host) {
        JSch jSch = new JSch();
        try {
            session = jSch.getSession(user, host, 22);
            session.setPassword(passwd);
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();
        } catch (JSchException e) {
            log.error(e.getMessage());
            return false;
        }
        return true;
    }

    /**
     * 远程链接Linux服务器，执行相关的命令
     */
    public static Map<String, String> runDistanceShell(String[] commands, String user, String passwd, String host) {
        if (!connect(user, passwd, host)) {
            return null;
        }
        HashMap<String, String> map = new HashMap<>();
        StringBuilder stringBuilder;
        BufferedReader reader = null;
        Channel channel = null;
        try {
            for (String command : commands) {
                stringBuilder = new StringBuilder();
                channel = session.openChannel("exec");
                ((ChannelExec) channel).setCommand(command);
                channel.setInputStream(null);
                ((ChannelExec) channel).setErrStream(System.err);
                channel.connect();
                InputStream inputStream = channel.getInputStream();
                reader = new BufferedReader(new InputStreamReader(inputStream));
                String buf;
                while ((buf = reader.readLine()) != null) {
                    //舍弃PID，进程信息
                    if (buf.contains("PID")) {
                        break;
                    }
                    stringBuilder.append(buf.trim()).append(LINE_SEPARATOR);
                }
                map.put(command, stringBuilder.toString());
            }
        } catch (IOException | JSchException e) {
            log.error(e.getMessage());
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage());
            }
            if (channel != null) {
                channel.disconnect();
            }
            session.disconnect();
        }

        return map;
    }

    /**
     * 处理shell返回信息
     */
    public static String disposeResultMessage(Map<String, String> result) {
        StringBuilder buffer = new StringBuilder();
        for (String command : COMMANDS) {
            String commandResult = result.get(command);
            if (commandResult == null) {
                continue;
            }
            if (command.equalsIgnoreCase(CPU_MEM_SHELL)) {
                String[] split = commandResult.split(LINE_SEPARATOR);
                for (String line : split) {
                    line = line.toUpperCase();
                    //处理CPU
                    if (line.startsWith("%CPU(S):")) {
                        String cpuStr = "CPU 用户使用占有率:";
                        try {
                            cpuStr += line.split(":")[1].split(",")[0].replace("US", "");
                        } catch (Exception e) {
                            log.error(e.getMessage());
                            cpuStr += "计算过程出错！";
                        }
                        buffer.append(cpuStr).append(LINE_SEPARATOR);
                    }
                    //处理内存
                    else if (line.startsWith("KIB MEM")) {
                        String memStr = "内存使用情况:";
                        try {
                            memStr += line.split(":")[1].replace("TOTAL", "总计")
                                    .replace("USED", "已使用")
                                    .replace("FREE", "空闲")
                                    .replace("BUFFERS", "缓存");
                        } catch (Exception e) {
                            log.error(e.getMessage());
                            memStr += "计算过程出错";
                            buffer.append(memStr).append(LINE_SEPARATOR);
                        }
                        buffer.append(memStr).append(LINE_SEPARATOR);
                    }
                }
            } else if (command.equalsIgnoreCase(FILES_SHELL)) {
                //处理磁盘系统
                buffer.append("系统磁盘状态:");
                try {
                    buffer.append(disposeFilesSystem(commandResult)).append(LINE_SEPARATOR);
                } catch (Exception e) {
                    log.error(e.getMessage());
                    buffer.append("计算过程出错").append(LINE_SEPARATOR);
                }
            }
        }
        return buffer.toString();
    }

    /**
     * 处理磁盘状态
     */
    private static List<String> disposeFilesSystem(String commandResult) {
        String[] split = commandResult.split(LINE_SEPARATOR);
        String text = null;
        for (String s : split) {
            if (s.contains(MSG)) {
                text = s;
                break;
            }
        }
        if (text == null) {
            return null;
        }
        String[] s = text.trim().split(" ");
        //遍历s
        List<String> arr = new ArrayList<>();
        for (int i = 1; i < s.length - 1; i++) {
            if (!s[i].equals("")) {
                arr.add(s[i]);
            }
        }
        if (arr.size() >= 4) {
            return arr;
        }
        return null;
    }

    public static void main(String[] args) {
        Map<String, String> shell1 = runDistanceShell(COMMANDS, "root", "?Mtjds992799", "122.51.173.82");
        Map<String, String> shell2 = runDistanceShell(COMMANDS, "root", "13350803936wubo!", "203.195.202.209");
        Map<String, String> shell3 = runDistanceShell(COMMANDS, "root", "Cchenqi,666", "116.62.111.151");
        Map<String, String> shell4 = runDistanceShell(COMMANDS, "root", "?Mtjds992799", "118.178.186.225");
        Map<String, String> shell5 = runDistanceShell(COMMANDS, "root", "13350803936wubo!", "47.113.120.20");
        System.out.println(disposeResultMessage(shell1) + "\n");
        System.out.println(disposeResultMessage(shell2) + "\n");
        System.out.println(disposeResultMessage(shell3) + "\n");
        System.out.println(disposeResultMessage(shell4) + "\n");
        System.out.println(disposeResultMessage(shell5) + "\n");

    }
}
